package com.ytjj.qmyx.mall.service.h5.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.enums.ProductActivityStatusEnums;
import com.ytjj.qmyx.mall.mapper.CouponRecordsDao;
import com.ytjj.qmyx.mall.mapper.CouponRecordsMapper;
import com.ytjj.qmyx.mall.mapper.ProductDao;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.CouponRecords;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.ProductExample;
import com.ytjj.qmyx.mall.model.response.ActivityProductResponse;
import com.ytjj.qmyx.mall.model.response.H5UserCouponResponse;
import com.ytjj.qmyx.mall.model.response.ProductResponse;
import com.ytjj.qmyx.mall.model.response.UserCouponResponse;
import com.ytjj.qmyx.mall.service.h5.H5CashCouponService;
import com.ytjj.qmyx.mall.utils.FakeUserUtil;
import com.ytjj.qmyx.mall.utils.RandomUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class H5CashCouponServiceImpl implements H5CashCouponService {

    @Resource
    private ProductDao productDao;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private CouponRecordsDao couponRecordsDao;

    @Resource
    private CouponRecordsMapper couponRecordsMapper;

    @Resource
    private FakeUserUtil fakeUserUtil;

    @Resource
    private SysConfigUtil sysConfigUtil;

    @Override
    public List<ProductResponse> getCouponList(Integer pageNum, Integer pageSize,Integer columnId,Integer flag) {
        List<ProductResponse> cashCouponList = this.getCashCouponList(pageNum,pageSize,columnId);
        if(1==flag) {//打乱顺序
            // 优惠券置顶数量
            List<ProductResponse> allList = new ArrayList<>();
            Integer cashCouponTopNum = Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.CASH_COUPON_TOP_NUM));
            List<ProductResponse> couponTopList = cashCouponList.stream()
                    .limit(cashCouponTopNum)
                    .collect(Collectors.toList());
            Collections.shuffle(couponTopList);
            allList.addAll(couponTopList);
            if (cashCouponList.size() > cashCouponTopNum) {
                List<ProductResponse> couponList = cashCouponList.subList(cashCouponTopNum, cashCouponList.size());
                Collections.shuffle(couponList);
                allList.addAll(couponList);
            }
            return allList;
        }
        return cashCouponList;
    }

    @Override
    public H5UserCouponResponse getUserCouponList(Integer obtain) {
        if(1==obtain){//自动领取前5个商品
            List<ProductResponse> cashCouponList = this.getCashCouponList(1,5,null);
            cashCouponList.stream().forEach(item -> {
                obtainCoupon(item.getId());
            });
        }
        H5UserCouponResponse userCouponResponse = new H5UserCouponResponse();
        String token;
        String source = TokenUtil.getSource();
        if ("h5".equals(source)||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        Date nowDate = new Date();

        // 查询待使用
        List<CouponRecords> unUseRecordList = couponRecordsDao.selectUsage(0, token, nowDate, source);
        // 查询已使用
        List<CouponRecords> usedRecordList = couponRecordsDao.selectUsage(3, token, nowDate, source);
        BigDecimal usedPrice = new BigDecimal(0);
        BigDecimal unUsedPrice = new BigDecimal(0);
        List<ProductResponse> unUseProductList = unUseRecordList.stream()
                .map(item -> {
                    Product product = productMapper.selectByPrimaryKey(item.getProductId());
                    ProductResponse productResponse = new ProductResponse(product);
                    productResponse.setIsReceive(2);
                    productResponse.setOverdueTime(item.getOverdueTime());
                    return productResponse;
                }).collect(Collectors.toList());
        for(ProductResponse product:unUseProductList){
            // 累加金额
            unUsedPrice=unUsedPrice.add(product.getActivityMax());
        }
        List<ProductResponse> usedProductList = usedRecordList.stream()
                .map(item -> {
                    Product product = productMapper.selectByPrimaryKey(item.getProductId());
                    ProductResponse productResponse = new ProductResponse(product);
                    productResponse.setIsReceive(2);
                    productResponse.setOverdueTime(item.getOverdueTime());
                    return productResponse;
                }).collect(Collectors.toList());
        for(ProductResponse product:usedProductList){
            // 累加金额
            usedPrice=usedPrice.add(product.getActivityMax());
        }
        BigDecimal totalPrice = usedPrice.add(unUsedPrice).setScale(2, BigDecimal.ROUND_UP);
        //待使用
        userCouponResponse.setNotUseCouponList(unUseProductList);
        userCouponResponse.setUsedCouponList(usedProductList);
        userCouponResponse.setTotalPrice(totalPrice);
        userCouponResponse.setUsed(usedPrice);
        userCouponResponse.setNotUsed(unUsedPrice);
        return userCouponResponse;
    }

    @Override
    public CouponRecords obtainCoupon(Integer productId) {
        Date date = new Date();
        String token;
        String source = TokenUtil.getSource();
        if ("h5".equals(source)||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        Integer count = couponRecordsDao.selectIsReceive(productId, token, date, source);
        if (count > 0) {
            throw new ApiException("该优惠券已经领取,请勿重复领取!");
        }

        int couponExpirationTime = 24*60;
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, couponExpirationTime);
        // 当前时间 + 过期时间
        Date overdueTime = nowTime.getTime();

        CouponRecords couponRecords = new CouponRecords();
        couponRecords.setProductId(productId);
        couponRecords.setSource(source);
        couponRecords.setToken(token);
        // 领取时间
        couponRecords.setReceiveTime(date);
        // 到期时间
        couponRecords.setOverdueTime(overdueTime);
        // 时长
        couponRecords.setDurationTime(couponExpirationTime);
        couponRecordsMapper.insert(couponRecords);
        return couponRecords;
    }

    private List<ProductResponse> getCashCouponList(Integer pageNum, Integer pageSize,Integer columnId) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.queryActivityProductList(ActivityTypeEnums.CASH_COUPON.name(),columnId,null,null,
                null,TokenUtil.getPlatformData(),null,null,null,null);

        return productList.stream()
                .map(item -> {
                    ProductResponse productResponse = new ProductResponse(item);
                    try {
                        BigDecimal baseStock = new BigDecimal(Optional.ofNullable(productResponse.getStock()%17).orElse(0))
                                .multiply(new BigDecimal(100))
                                .divide(new BigDecimal(5678), 2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal stockProgress = new BigDecimal(1)
                                .subtract(baseStock).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                        if(stockProgress.intValue()>=100||stockProgress.intValue()<=0){
                            productResponse.setStockProgress(60);
                        }else {
                            productResponse.setStockProgress(stockProgress.intValue());
                        }
                    } catch (ApiException e) {
                        productResponse.setStockProgress(80);
                    }
                    int i = RandomUtil.getSectionNum(1, 3);
                    switch (i) {
                        case 1:
                            productResponse.setTips("限时限量");
                            break;
                        case 2:
                            productResponse.setTips("7天无理由退换");
                            break;
                        case 3:
                            productResponse.setTips("顺丰包邮");
                            break;
                    }
                    return productResponse;
                })
                .collect(Collectors.toList());
    }
}
